package fr.inserm.um915.jimpute.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class IOUtils
{	
public static BufferedReader openUrl(String url) throws IOException
	{
	if(!(url.startsWith("http://") || url.startsWith("ftp://") || url.startsWith("https://")))
		{
		return openReader(new File(url));
		}
	InputStream in=new URL(url).openStream();
	if(url.endsWith(".gz"))
		{
		in=new GZIPInputStream(in);
		}
	return new BufferedReader(new InputStreamReader(in));
	}	
	
	
public static BufferedReader openReader(File f) throws IOException
	{
	if(f.getName().endsWith(".gz"))
		{
		return new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(f))));
		}
	return new BufferedReader(new FileReader(f));
	}

public static PrintStream openWriter(File f) throws IOException
	{
	
	if(f.getName().endsWith(".gz"))
		{
		return new PrintStream(new GZIPOutputStream(new FileOutputStream(f)))
			{
			@Override
			public void close() {
				try {
					GZIPOutputStream gz=(GZIPOutputStream)this.out;
				 gz.finish();
				 gz.flush();
				 gz.close();
				} catch(Throwable err)
					{
					err.printStackTrace();
					}
				}
			};
		}
	return new PrintStream(f);
	}


public static OutputStream createNullOutputStream()
	{
	return new OutputStream()
		{
		@Override
		public void write(byte[] arg0) throws IOException
			{
			}
		@Override
		public void write(int b) throws IOException {
			
			}
		@Override
		public void write(byte[] arg0, int arg1, int arg2)
			throws IOException
			{
			}
		};
	}

public static PrintStream createNullPrintStream()
	{
	return new PrintStream(createNullOutputStream());
	}

}
